package com.rickpan.controller;

import com.rickpan.dto.common.ApiResponse;
import com.rickpan.entity.TransferRecord;
import com.rickpan.service.TransferRecordService;
import com.rickpan.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 传输记录控制器
 */
@RestController
@RequestMapping("/api/transfer")
public class TransferController {

    private static final Logger logger = LoggerFactory.getLogger(TransferController.class);

    @Autowired
    private TransferRecordService transferRecordService;

    /**
     * 创建传输记录
     */
    @PostMapping("/records")
    public ApiResponse<TransferRecord> createTransferRecord(@RequestBody Map<String, Object> request) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();

            // 解析请求参数
            String sessionId = (String) request.get("sessionId");
            String fileName = (String) request.get("fileName");
            String originalName = (String) request.get("originalName");
            Long fileSize = Long.valueOf(request.get("fileSize").toString());
            String transferType = (String) request.get("transferType");
            String transferStatus = (String) request.get("transferStatus");
            BigDecimal progressPercentage = new BigDecimal(request.get("progressPercentage").toString());
            Long transferredBytes = Long.valueOf(request.get("transferredBytes").toString());
            String startTimeStr = (String) request.get("startTime");
            String endTimeStr = (String) request.get("endTime");

            // 创建传输记录
            TransferRecord record = new TransferRecord();
            record.setUserId(userId);
            record.setSessionId(sessionId);
            record.setFileName(fileName);
            record.setOriginalName(originalName);
            record.setFileSize(fileSize);
            record.setTransferType(TransferRecord.TransferType.valueOf(transferType));
            record.setTransferStatus(TransferRecord.TransferStatus.valueOf(transferStatus));
            record.setProgressPercentage(progressPercentage);
            record.setTransferredBytes(transferredBytes);

            // 解析时间
            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
            if (startTimeStr != null) {
                record.setStartTime(LocalDateTime.parse(startTimeStr.replace("Z", ""), formatter));
            }
            if (endTimeStr != null) {
                record.setEndTime(LocalDateTime.parse(endTimeStr.replace("Z", ""), formatter));
            }

            TransferRecord savedRecord = transferRecordService.saveTransferRecord(record);

            logger.info("创建传输记录成功: userId={}, sessionId={}, fileName={}, type={}",
                       userId, sessionId, fileName, transferType);

            return ApiResponse.success(savedRecord);
        } catch (Exception e) {
            logger.error("创建传输记录失败", e);
            return ApiResponse.error("创建传输记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取传输历史记录
     */
    @GetMapping("/history")
    public ApiResponse<Page<TransferRecord>> getTransferHistory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            Page<TransferRecord> history = transferRecordService.getTransferHistory(userId, page, size);
            
            logger.info("获取传输历史记录: userId={}, page={}, size={}, total={}", 
                       userId, page, size, history.getTotalElements());
            
            return ApiResponse.success(history);
        } catch (Exception e) {
            logger.error("获取传输历史记录失败", e);
            return ApiResponse.error("获取传输历史记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前进行中的传输
     */
    @GetMapping("/active")
    public ApiResponse<List<TransferRecord>> getActiveTransfers() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            List<TransferRecord> activeTransfers = transferRecordService.getActiveTransfers(userId);
            
            logger.info("获取进行中传输: userId={}, count={}", userId, activeTransfers.size());
            
            return ApiResponse.success(activeTransfers);
        } catch (Exception e) {
            logger.error("获取进行中传输失败", e);
            return ApiResponse.error("获取进行中传输失败: " + e.getMessage());
        }
    }

    /**
     * 获取今日传输记录
     */
    @GetMapping("/today")
    public ApiResponse<List<TransferRecord>> getTodayTransfers() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            List<TransferRecord> todayTransfers = transferRecordService.getTodayTransfers(userId);
            
            logger.info("获取今日传输记录: userId={}, count={}", userId, todayTransfers.size());
            
            return ApiResponse.success(todayTransfers);
        } catch (Exception e) {
            logger.error("获取今日传输记录失败", e);
            return ApiResponse.error("获取今日传输记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取传输统计信息
     */
    @GetMapping("/statistics")
    public ApiResponse<TransferRecordService.TransferStatistics> getTransferStatistics() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            TransferRecordService.TransferStatistics statistics = 
                transferRecordService.getTransferStatistics(userId);
            
            logger.info("获取传输统计: userId={}, completed={}, failed={}, inProgress={}", 
                       userId, statistics.getCompletedCount(), 
                       statistics.getFailedCount(), statistics.getInProgressCount());
            
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            logger.error("获取传输统计失败", e);
            return ApiResponse.error("获取传输统计失败: " + e.getMessage());
        }
    }

    /**
     * 清除已完成的传输记录
     */
    @DeleteMapping("/completed")
    public ApiResponse<String> clearCompletedRecords() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            transferRecordService.clearCompletedRecords(userId);
            
            logger.info("清除已完成传输记录: userId={}", userId);
            
            return ApiResponse.success("已完成传输记录已清除");
        } catch (Exception e) {
            logger.error("清除已完成传输记录失败", e);
            return ApiResponse.error("清除已完成传输记录失败: " + e.getMessage());
        }
    }

    /**
     * 取消传输（开发中）
     */
    @PostMapping("/cancel/{recordId}")
    public ApiResponse<String> cancelTransfer(@PathVariable Long recordId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("取消传输请求: userId={}, recordId={}", userId, recordId);

            // 删除传输记录
            transferRecordService.deleteTransferRecord(recordId);

            return ApiResponse.success("传输已取消");
        } catch (Exception e) {
            logger.error("取消传输失败", e);
            return ApiResponse.error("取消传输失败: " + e.getMessage());
        }
    }

    /**
     * 删除传输记录
     */
    @DeleteMapping("/records/{recordId}")
    public ApiResponse<String> deleteTransferRecord(@PathVariable Long recordId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            logger.info("删除传输记录请求: userId={}, recordId={}", userId, recordId);

            // 删除传输记录
            transferRecordService.deleteTransferRecord(recordId);

            return ApiResponse.success("传输记录已删除");
        } catch (Exception e) {
            logger.error("删除传输记录失败", e);
            return ApiResponse.error("删除传输记录失败: " + e.getMessage());
        }
    }
}
